package dryven.view.engine.parser.parts;

import java.io.IOException;
import java.io.Writer;

import dryven.codegen.asm.MethodBuilder;
import dryven.view.ViewDataDictionary;
import dryven.view.engine.expression.ExpressionCompilationException;
import dryven.view.engine.expression.CompiledViewExpression;
import dryven.view.engine.expression.ViewExpression;
import dryven.view.engine.parser.ViewComponentLocator;
import dryven.view.engine.parser.ViewDataDeclarationCollection;

public class ExpressionPart implements CompiledViewPart {

	private String _expression;
	private CompiledViewExpression _compiledExpression;
	
	public ExpressionPart(String expression) {
		super();
		_expression = expression;
	}

	@Override
	public void evaluate(ViewDataDictionary viewData, Writer out, ViewDataDeclarationCollection declarations)
			throws IOException {
		out.write(_compiledExpression.evaluate(viewData).toString());
	}

	@Override
	public void writeInstructions(MethodBuilder builder) {
		// TODO Auto-generated method stub

	}

	@Override
	public void compile(ViewDataDeclarationCollection declarations, ViewComponentLocator locator) {
		ViewExpression expr = new ViewExpression(_expression, declarations.getViewDataDeclarations());
		try {
			_compiledExpression = expr.compile();
		} catch (ExpressionCompilationException e) {
			throw new RuntimeException(String.format("Could not compile expression '%s'", _expression),e);
		}
	}
	
	public String getExpression() {
		return _expression;
	}

}
